package com.doghome.mysb.web.interceptor;

import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.doghome.mysb.annotaion.CheckPermission;
import com.doghome.mysb.entity.User;
import com.doghome.mysb.service.UserService;
import com.doghome.mysb.utils.JwtUtil;

@Component
public class UserCheckInterceptor implements HandlerInterceptor {

	public static final Logger log = LoggerFactory.getLogger(UserCheckInterceptor.class);
	
	private StringRedisTemplate redisTemplate;
	private UserService userService;

	@Autowired
	public UserCheckInterceptor(StringRedisTemplate redisTemplate,UserService userService) {
		this.redisTemplate = redisTemplate;
		this.userService = userService;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.info("请求地址：" + request.getRequestURI());
		String token = request.getHeader("Authorization");
		log.info("token:" + token);
		//验证是否登录
		if (token == null || token.equals("")) {
			// 没有登录
			throw new RuntimeException("未登录");

		}
		
		//验证token
		Long userID = null;
		try {
			userID = JwtUtil.getUserID(token);
		}catch (SignatureVerificationException e) {
			throw new RuntimeException("验签错误");
		}catch (TokenExpiredException e) {
			throw new RuntimeException("登录超时");
		}
		String serverToken = redisTemplate.opsForValue().get(userID.toString());
		if(serverToken == null || !token.equals(serverToken)) {
			throw new RuntimeException("验签错误");
		}
		
		
		//toke延期
		Date exp = JwtUtil.getExpires(token);
		if(exp.getTime() - System.currentTimeMillis() <= 5 * 60 * 1000 ) {
			//进行token置换
			String newToken = JwtUtil.createToken(userID);
			redisTemplate.opsForValue().set(userID.toString(), newToken, 30, TimeUnit.MINUTES);
			response.setHeader("Access-Control-Expose-Headers", "x-token");
			response.setHeader("x-token", newToken);
		}
		
		//验证权限
		boolean isHandlerMethod = handler instanceof HandlerMethod;
		if (!isHandlerMethod) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		CheckPermission checkPermission = handlerMethod.getMethodAnnotation(CheckPermission.class);
		if(checkPermission == null) {
//			throw new RuntimeException("无权限");
			return true;
		}
		
		String[] roles =  checkPermission.value();
		log.info("角色："+Arrays.toString(roles));
		if(checkRole(userID, roles)) {
			return true;
		}else {
			throw new RuntimeException("权限不足");
		}
	}
	
	public boolean checkRole(long userID,String[] roles) {
		User user = userService.userByID(userID);
		for(String role : roles) {
			if(role.equals(user.getUserrole().toString())) {
				return true;
			}
		}
		return false;
	}

}
